﻿create PROCEDURE Sync.SP_Centers_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @Centers_Temp TABLE 
		(
			CenterID UniqueIdentifier,
			[CenterName] nvarchar(50),
				[GovernorateID] uniqueidentifier,
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @Centers_Temp 
	   SELECT	Tbl.Col.value('CenterID[1]','uniqueidentifier') CenterID,
                Tbl.Col.value('CenterName[1]', 'nvarchar(50)') [CenterName],
Tbl.Col.value('GovernorateID[1]', 'uniqueidentifier') [GovernorateID],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/Centers') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[Centers] ([CenterID],[CenterName],[GovernorateID])
	SELECT t.[CenterID],t.[CenterName],t.[GovernorateID]
	FROM  @Centers_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.Centers_Tracking s
        WHERE t.CenterID = s.CenterID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[Centers]
	SET [Centers].[CenterName] = t.[CenterName],[Centers].[GovernorateID] = t.[GovernorateID] 
	FROM [dbo].[Centers] s JOIN @Centers_Temp t 
    ON t.CenterID = s.CenterID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.Centers_Tracking r
				  WHERE t.CenterID = r.CenterID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[Centers]
    FROM @Centers_Temp t JOIN [dbo].[Centers] s
    ON t.CenterID = s.CenterID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END












GO